var bg = chrome.extension.getBackgroundPage();
var G = bg.SINA;
var img = new Image();
img.onload = function(){
	textToImg();
}
function changeColor() {
	var c = $("#text")[0];
	var ctx = c.getContext("2d");
	var red = $("#red").val();
	var green = $("#green").val();
	var blue = $("#blue").val();
	ctx.fillStyle = "rgb(" + red + "," + green + "," + blue + ")";
	ctx.fillRect(0, 0, 100, 100);
	$("#showcolor").val(ctx.fillStyle).css("color",ctx.fillStyle);
}

function change(id) {
	$("#" + id + "Show").val($("#" + id).val());
}

function textToImg() {
	var len = $('#len').val() || 30;
	var i = 0;
	var fontFml = $("input[name='fontFamily']:checked").val();
	var fontSize = $('#fontSize').val() || 15;
	var padding = $('#padding').val() || 1;
	padding = parseInt(padding);
	var fontWeight = 'normal';
	var txt = '动动鼠标即可把自己选中的图片、文字、以及视频的地址转播到新浪微博，您不必担心安全问题，因为这一切都是调用新浪微博官方API接口完成的.程序制作GodSon';
	var canvas = $('#canvas')[0];
	
	if (len > txt.length) {
		len = txt.length;
	}
	var fontHeight = fontSize * (3 / 2)* (Math.ceil(txt.length / len) + txt.split('\n').length - 1) + (padding * 2);
	var fontWidth = fontSize * len + (padding * 2);

    if(img.height != 0){
		var w = img.width,h = img.height;
		if(fontWidth < img.width){
			var bl = fontWidth/img.width;
			img.width = fontWidth;
			img.height = h*bl;
		}
	}
	
	canvas.width = fontWidth;
	canvas.height = fontHeight + img.height;
	var context = canvas.getContext('2d');
	context.clearRect(0, 0, canvas.width, canvas.height);
	context.fillStyle = "#fff";
	context.fillRect(0, 0, canvas.width, canvas.height);
	context.fillStyle = $("#showcolor").val();
	context.font = fontWeight + ' ' + fontSize + 'px ' + fontFml + ',arial';
	context.textBaseline = 'top';
	canvas.style.display = 'none';
	function fillTxt(text) {
		while (text.length > len) {
			var txtLine = text.substring(0, len);
			text = text.substring(len);
			context.fillText(txtLine, padding, padding + fontSize * (3 / 2) * i++,
				canvas.width);
		}
		
		context.fillText(text, padding, padding + fontSize * (3 / 2) * i, canvas.width);
	}
	var txtArray = txt.split('\n');
	for (var j = 0; j < txtArray.length; j++) {
		fillTxt(txtArray[j]);
		context.fillText('\n', 0, fontSize * (3 / 2) * i++, canvas.width);
	}
	
	if(img.height != 0){
		var x = 0;
		if(fontWidth - img.width > 0){
			x = (fontWidth - img.width)/2;
		}
		context.drawImage(img, x, fontHeight , img.width, img.height);
	}
	
	var imageData = context.getImageData(0, 0, canvas.width, canvas.height);
	var pre = new Image();
	pre.src = canvas.toDataURL("image/jpeg");
	$("#pre").html(pre);
}

function save(){
	var setting = $("form").formJson();
	if(img.src.indexOf('chrome-extension') == -1){
		setting['sy'] = img.src;
	}
	G.set('longSetting',JSON.stringify(setting));
	G.query_time = setting.timer*60*1000;
	if(G.interval){
		clearInterval(G.interval);
	}
	G.interval = setInterval(G.checkUpdates, G.query_time);
}

$(function(){
	var longSetting = G.get("longSetting");
	if(longSetting){
		longSetting = JSON.parse(longSetting);
		if(longSetting.sy && longSetting.sy !="" && longSetting.sy.indexOf('chrome-extension') == -1){
			img.src = longSetting.sy;
		}
		$("input:checked").attr("checked",false);
		$.each(longSetting,function(k,v){
			if(k != "fontFamily"){
				$("input[name='"+k+"']").val(v).change();
				$("input[name='"+k+"']").attr("checked",true);
			}else{
				$("input[value='"+v+"']").attr("checked",true);
			}
		});
	}else{
		save();
	}
	$("input[type!=file],select").change(textToImg);
	changeColor();
	textToImg();
	if(longSetting.sy && longSetting.sy !="" && longSetting.sy.indexOf('chrome-extension') == -1){
		$("#img_sy").html(img);
	}
	$(".cco").click(function(){
		var bgc = $(this).css("background-color");
		var bgca = bgc.replace("rgb(","").replace(")","").split(",");
		$("input[name=red]").val(parseInt(bgca[0]));
		$("input[name=green]").val(parseInt(bgca[1]));
		$("input[name=blue]").val(parseInt(bgca[2]));
		changeColor();
		textToImg();
	});
	
	window.onhashchange = function(event){
		var newTarget = event.newURL.split("#")[1];
		var oldTarget = event.oldURL.split("#")[1];
		
		$(".setting-nav li").removeClass("selected");
		$("."+newTarget).addClass("selected");
		$(".content").hide();
		$("#"+newTarget).show();
	}
	
	$(window).resize(setContentSize);
	setContentSize();
	
	$("input[type!=file]").change(save);
	
	$('#scolor input[type="range"]').change(changeColor);
	$('.sset').change(function(){
		change($(this).attr("id"));
	}).change();
	
	$('#wtimg').change(function(){
		showFile(this.files[0]);
	});
	
	$("#delsy").click(function(){
		img.src = '';
		save();
		setTimeout(function(){
			window.location.reload();
		},200);
	});
});

function setContentSize(){
var bd = $("body")[0];
$(".content").height(bd.clientHeight-100);
$(".content").width(bd.clientWidth-210);
}

function showFile(file) {
	var reader = new FileReader();
	reader.readAsDataURL(file);
	reader.onload = function (e) {
		img = new Image();
	    img.src = e.target.result;
		img.onload = function(){
			save();
			window.location.reload();
		}
	};
}

(function($) {
	$.fn.formJson = function() {
		var arrayValue = $(this).serializeArray();
		var json = {};
		$.each(arrayValue, function() {
			var item = this;
			if (json[item["name"]]) {
				json[item["name"]] = json[item["name"]] + "," + item["value"];
			} else {
				json[item["name"]] = item["value"];
			}
		});
		return json;
	};
})(jQuery);